package com.haople.sso.client.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.haople.sso.client.service.TicketValidateService;

public class TicketValidateServiceImpl implements TicketValidateService {
	private static final Logger logger=Logger.getLogger(TicketValidateServiceImpl.class);
	private static final String DEFAULT_REQUESTER_HEADER_USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8";
	
	private String ssoService;
	private String ticketValidateUrl;
	
	/**
	 * 票据验证
	 */
	public boolean ticketValidate(String userId, String ticket) {
		if(StringUtils.isEmpty(ssoService)){
			logger.error("ssoService is validate");
			return false;
		}
		if(StringUtils.isEmpty(ticketValidateUrl)){
			logger.error("ticketValidateUrl is validate");
			return false;
		}
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost=new HttpPost(ticketValidateUrl);
			httpPost.setHeader("User-Agent", DEFAULT_REQUESTER_HEADER_USER_AGENT);
			   // 创建参数队列    
	        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
	        formparams.add(new BasicNameValuePair("userId", userId));  
	        formparams.add(new BasicNameValuePair("ticket", ticket));  
	        UrlEncodedFormEntity uefEntity=new UrlEncodedFormEntity(formparams, "UTF-8");
	        httpPost.setEntity(uefEntity);
			CloseableHttpResponse httpResponse=httpclient.execute(httpPost);
			HttpEntity entity = httpResponse.getEntity(); 
			if(entity==null){
				return false;
			}
			String responseContent=EntityUtils.toString(entity, "utf-8");
			logger.info("ticketValidate--response--content-->"+responseContent);
			if(StringUtils.isEmpty(responseContent)){
				return false;
			}
			JSONObject jsonObject=JSONObject.parseObject(responseContent);
			Integer validateStatus=jsonObject.getInteger("validate_status");
			if(validateStatus!=null && validateStatus.intValue()>0){
				return true;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(httpclient!=null){
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
	
	public void setSsoService(String ssoService) {
		this.ssoService = ssoService;
		ticketValidateUrl=ssoService+"/ticketValidate";
	}

	/**
	 * 获取登录地址
	 * @return
	 */
	public String getLoginUrl(){
		return ssoService+"/";
	}

	
}
